﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Tomato.Maths
{
    public class RandomValueSequence
    {
        private List<RandomValue> randomValues = new List<RandomValue>();

        public long TotalCount { get; set; }


        public RandomValue GetRandomValue(int index)
        {
            return randomValues[index];
        }

        public void AddRandomValue(long lastHitIndex, int interval, double probability, double deviation)
        {
            if (interval == 0)
            {
                interval = (int)((1.0 / probability) * (1 - deviation + 2 * deviation * GetRandom().NextDouble()));
            }

            randomValues.Add(new RandomValue() { Probability = probability, LastHitIndex = lastHitIndex, Interval = interval, Deviation = deviation });
            EliminateConflicts(randomValues.Last());
        }

        private void EliminateConflicts(RandomValue value)
        {
            foreach (RandomValue rv in randomValues.Where(i => i != value).OrderBy(i => i.NextHitIndex))
            {
                if (value.NextHitIndex == rv.NextHitIndex)
                {
                    value.Interval++;
                }
            }
        }


        private static Random random;

        private static Random GetRandom()
        {
            if (random == null)
            {
                random = new Random((DateTime.Now.Minute + DateTime.Now.Second + 1) * (DateTime.Now.Millisecond + 1));
            }

            return random;
        }


        public int NextValue()
        {
            TotalCount++;

            RandomValue value = randomValues.FirstOrDefault(i => TotalCount == i.NextHitIndex);
            if (value == null)
            {
                return -1;
            }

            value.LastHitIndex = TotalCount;
            value.ComputeNextInterval(GetRandom().NextDouble());
            EliminateConflicts(value);

            return randomValues.IndexOf(value);
        }
    }
}
